package com.itcam.project.client;

import com.itcam.iahcommon.enums.ErrorCode;
import com.itcam.iahcommon.exception.BusinessException;
import com.volcengine.ark.runtime.model.bot.completion.chat.BotChatCompletionRequest;
import com.volcengine.ark.runtime.model.bot.completion.chat.BotChatCompletionResult;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class BotClient {
    private final ArkService service;
    private final String botId;

    public BotClient(
            @Value("${ark.api-key}") String apiKey,
            @Value("${ark.base-url}") String baseUrl,
            @Value("${ark.bot-id}") String botId) {
        
        this.botId = botId;
        
        ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS);
        Dispatcher dispatcher = new Dispatcher();
        
        this.service = ArkService.builder()
                .dispatcher(dispatcher)
                .connectionPool(connectionPool)
                .baseUrl(baseUrl.endsWith("/") ? baseUrl : baseUrl + "/")
                .apiKey(apiKey)
                .build();
    }

    public String doChat(String message) {
        List<ChatMessage> messages = new ArrayList<>();
        messages.add(ChatMessage.builder()
                .role(ChatMessageRole.SYSTEM)
                .content("你是豆包，是由字节跳动开发的 AI 人工智能助手")
                .build());
        messages.add(ChatMessage.builder()
                .role(ChatMessageRole.USER)
                .content(message)
                .build());

        BotChatCompletionRequest request = BotChatCompletionRequest.builder()
                .botId(botId)
                .messages(messages)
                .build();

        BotChatCompletionResult result = service.createBotChatCompletion(request);
        
        if (result == null || result.getChoices() == null || result.getChoices().isEmpty()) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI响应数据异常");
        }
        
        // 处理参考文献（可选）
        if (result.getReferences() != null) {
            result.getReferences().forEach(ref -> 
                System.out.println("参考来源: " + ref.getUrl()));
        }
        
        return (String) result.getChoices().get(0).getMessage().getContent();
    }

    @PreDestroy
    public void shutdown() {
        service.shutdownExecutor();
    }
}